package com.gali.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @Auther: gali
 * @Date: 2022-08-23 17:22
 * @Description:
 */
class BankAccount{
    String bankName="ICBC";
    public volatile int money=0;
    public void add(){
        money++;
    }
    AtomicIntegerFieldUpdater<BankAccount> fieldUpdater=
            AtomicIntegerFieldUpdater.newUpdater(BankAccount.class,"money");
    public void transMoney(BankAccount bankAccount){
        fieldUpdater.getAndIncrement(bankAccount);
    }
}
public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    for (int j = 0; j < 1000; j++) {
                        bankAccount.transMoney(bankAccount);
                    }
                } finally {
                    countDownLatch.countDown();
                }
            },"a").start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+bankAccount.money);
    }
}
